package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.User;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class UserDao {

	private DBHelp<User> db = new DBHelp<User>();
	
	
	public int save(String name,String pwd) {
		String sql = "insert into t_user(name,pwd) values(?,?)";
		return db.executeUpdate(sql, name,pwd);
	}
	
	
	public int del(String id) {
		String sql = "delete from t_user where id = ?";
		return db.executeUpdate(sql, id);
	}
	
	
	public int edit(String id,String name,String pwd) {
		String sql = "update t_user set name = ?,pwd = ? where id = ?";
		return db.executeUpdate(sql, name,pwd,id);
	}
	
	public User findById(String id) {
		String sql = "select id,name,pwd from t_user where id = ?";
		return db.queryForObject(sql, new UserMapper(), id);
	}
	
	public User login(String name,String pwd){
		String sql = "select id,name,pwd from t_user where name = ? and pwd = ?";
		return db.queryForObject(sql,new RowMapper<User>(){
			public User mapRow(ResultSet rs) throws SQLException {
				User user = new User();
				user.setName(rs.getString("name"));
				user.setPwd(rs.getString("pwd"));
				return user;
			}}, name,pwd);
		
	}
	
	public List<User> findAll(){
		String sql = "select id,name,pwd from t_user";
		return db.queryForList(sql, new UserMapper2());
	}
}

class UserMapper2 implements RowMapper<User>{

	public User mapRow(ResultSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("id"));
		user.setName(rs.getString("name"));
		user.setPwd(rs.getString("pwd"));
		return user;
	}
	
}


